package com.lpc.framework.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * Json工具类，使用jackson包处理
 * 
 * @author jiangjinlong
 */
public class JsonUtil {
    private static ObjectMapper mapper;
    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    /**
     * 静态代码块，初始化mapper
     */
    static {
        mapper =
                Jackson2ObjectMapperBuilder
                        .json()
                        .simpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                                DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                        // 允许转义
                        .featuresToEnable(Feature.ALLOW_UNQUOTED_CONTROL_CHARS).build();
    }

    /**
     * 将对象转化为json
     * 
     * @param Object对象
     * @return
     * @throws IOException
     */
    public static String object2Json(Object o) {
        String jsonValue = null;
        Writer strWriter = new StringWriter();
        try {
            mapper.writeValue(strWriter, o);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        jsonValue = strWriter.toString();
        return jsonValue;
    }

    /**
     * 将对象转化为json
     * 
     * @param Object对象
     * @return
     */
    public static String stringObject2Json(Object o) {
        String jsonValue = null;
        try {
            Writer strWriter = new StringWriter();
            mapper.writeValue(strWriter, o);
            jsonValue = strWriter.toString().replace("\\", "");

        } catch (Exception e) {
            logger.error("对象转换为json时出错", e);
        }

        return jsonValue;
    }

    /**
     * 
     * @param jsonValue json字符串
     * @param classValue object.class
     * @return
     */
    public static Object json2Object(String jsonValue, Class<?> classValue) {
        Object o = null;
        try {
            if (jsonValue != null) {
                o = mapper.readValue(jsonValue, classValue);
            }

        } catch (Exception e) {
            logger.error("json转换为对象时出错", e);
        }
        return o;
    }

    /**
     * 复杂类型的json转对象
     * 
     * @param jsonValue
     * @param type
     * @return
     * @throws Exception
     */
    public static <T> Object json2Object(String jsonValue, TypeReference<T> type) {
        Object o = null;
        try {
            if (jsonValue != null) {
                o = mapper.readValue(jsonValue, type);
            }

        } catch (Exception e) {
            logger.error("json转换为对象时出错", e);
        }
        return o;
    }

    /**
     * 将字符串转化成List<?>数组
     * 
     * @param jsonValue json字符串
     * @return
     */
    public static List<?> json2List(String jsonValue) {
        List<?> resultArr = new ArrayList<Object>();
        TypeReference<List<Object>> typeRef = null;
        try {
            if (jsonValue != null) {

                typeRef = new TypeReference<List<Object>>() {
                };
                resultArr = mapper.readValue(jsonValue, typeRef);

            }
        } catch (Exception e) {
            logger.error("json转换为list时出错", e);
        }
        return resultArr;
    }

    /**
     * 适用嵌套类型
     */
    public static List<?> json2List(String jsonValue, @SuppressWarnings("rawtypes") TypeReference typeRef) {
        List<?> resultArr = new ArrayList<Object>();
        try {
            if (jsonValue != null) {
                resultArr = mapper.readValue(jsonValue, typeRef);
            }
        } catch (Exception e) {
            logger.error("json换为list时出错", e);
        }
        return resultArr;
    }

    /**
     * 将list<Object>转化成json字符串
     * 
     * @param objList
     * @return
     */
    public static String list2Json(List<?> objList) {
        String resultJson = null;
        try {

            if (objList.isEmpty()) {
                return null;
            } else {
                resultJson = mapper.writeValueAsString(objList);
            }

        } catch (Exception e) {
            logger.error("list转换为json时出错", e);
        }
        return resultJson;
    }

    public static void writeStringAsJson(HttpServletResponse response, Object result) {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(mapper.writeValueAsString(result));
        } catch (Exception e) {
            logger.error("writeStringAsJson has error : ", e);
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }
}
